<template>
    <div class="container">
        <!-- 搜索区域 -->
        <div class="search-area">
            <el-input style="width: 300px;" v-model="inputyan" placeholder="请输入用户名"></el-input>
            <el-input style="width: 300px; margin-left: 10px;" v-model="input7" placeholder="请输入用户id"></el-input>
            <el-input style="width: 300px; margin-left: 10px;" v-model="input8" placeholder="请输入手机号"></el-input>
            <el-button class="annu" type="primary" icon="el-icon-search" @click="searchData">查找</el-button>
            <el-button class="annu2" type="primary" icon="el-icon-download" @click="exportData">导出</el-button>
        </div>
        <!-- 表格区域 -->
        <div class="table-wrapper">
            <el-table
                    :data="list"
                    border
                    style="width: 100%"
                    :row-class-name="tableRowClassName"
                    :key="page + '-' + limit"
                    @sort-change="handleSortChange">
                <el-table-column
                        fixed
                        prop="id"
                        label="用户id"
                        width="95"
                        sortable="custom">
                </el-table-column>
                <el-table-column
                        prop="nickname"
                        label="用户昵称"
                        width="145">
                </el-table-column>
                <el-table-column
                        prop="avatar"
                        label="用户头像"
                        width="80">
                    <template slot-scope="scope">
                        <img :src="scope.row.avatar" alt="用户头像" style="width: 50px; height: 50px; border-radius: 50%;">
                    </template>
                </el-table-column>
                <el-table-column
                        prop="mobile"
                        label="手机号码"
                        width="150">
                </el-table-column>
                <el-table-column
                        prop="gender"
                        label="性别"
                        width="140">
                    <template slot-scope="scope">
                        <el-tag type="info" size="small">{{ formatGender(scope.row, null, scope.row.gender) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="addTime"
                        label="生日"
                        width="140"
                        :formatter="formatDate">
                </el-table-column>
                <el-table-column
                        prop="userLevel"
                        label="用户等级"
                        width="130">
                    <template slot-scope="scope">
                        <el-tag type="info" size="small">{{ formatUserLevel(scope.row, null, scope.row.userLevel) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="status"
                        label="状态"
                        width="140">
                    <template slot-scope="scope">
                        <el-tag type="info" size="small">{{ formatStatus(scope.row, null, scope.row.status) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                        label="操作"
                        width="256.5">
                    <template slot-scope="scope">
                        <el-button class="edit-button"  @click="showDetail(scope.row)">详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div v-if="list.length === 0" style="text-align: center; padding: 20px;">
                暂无数据
            </div>
        </div>
        <!-- 分页区域 -->
        <div class="block">
            <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="page"
                :page-sizes="[3, 20, 30, 40]"
                :page-size="limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
        <!-- 详情弹框 -->
        <el-dialog
            :visible.sync="dialogVisible"
            title="用户详情"
            width="45%">
            <p>用户名</p><el-input disabled v-model="selectedUser.nickname" placeholder="请输入内容"></el-input>
            <p>用户手机</p><el-input v-model="selectedUser.mobile" placeholder="请输入内容"></el-input>
            <p>用户性别</p>
            <el-select v-model="selectedUser.gender" placeholder="请选择性别">
                <el-option
                    v-for="option in genderOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value">
                </el-option>
            </el-select>
            <p>用户等级</p>
            <el-select v-model="selectedUser.userLevel" placeholder="请选择用户等级">
                <el-option
                    v-for="option in userLevelOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value">
                </el-option>
            </el-select>
            <p>用户状态</p>
            <el-select v-model="selectedUser.status" placeholder="请选择用户状态">
                <el-option
                    v-for="option in statusOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value">
                </el-option>
            </el-select>
            <template #content>
                <div>
            
                </div>
            </template>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button @click="queding">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { huiyuan, searchUserList, getUserById, bianji } from '@/api/yonghuguanli/huiyuanguanli.js';
import dayjs from 'dayjs';

export default {
    data() {
        return {
            inputyan: '',
            input7: '',
            input8: '',
            list: [],
            page: 1,
            limit: 20,
            total: 0,
            sort: 'add_time',
            order: 'desc',
            token: 'your_token_here',
            dialogVisible: false,
            selectedUser: {},
            genderOptions: [
                { value: 1, label: '男' },
                { value: 2, label: '女' },
                { value: 3, label: '未知' }
            ],
            userLevelOptions: [
                { value: 0, label: '普通用户' },
                { value: 1, label: 'VIP用户' },
                { value: 2, label: '高级用户' }
            ],
            statusOptions: [
                { value: 0, label: '可用' },
                { value: 1, label: '禁用' },
                { value: 2, label: '注销' }
            ]
        };
    },
    created() {
        this.fetchData();
    },
    mounted() {
        const params = {
            username: this.inputyan,
            page: this.page,
            limit: this.limit,
            sort: this.sort,
            order: this.order,
            token: this.token
        };
        huiyuan(params)
          .then((res) => {
                console.log('huiyuan 请求响应:', res);
                if (res.data && Array.isArray(res.data.list)) {
                    const formattedList = res.data.list.map(item => {
                        return {
                            ...item,
                            addTime: dayjs(item.addTime).format('YYYY-MM-DD HH:mm:ss'),
                            lastLoginTime: dayjs(item.lastLoginTime).format('YYYY-MM-DD HH:mm:ss'),
                            updateTime: dayjs(item.updateTime).format('YYYY-MM-DD HH:mm:ss')
                        };
                    });
                    this.list = formattedList;
                    this.total = res.data.total;
                } else {
                    console.error('huiyuan 接口返回的数据格式不符合预期', res.data);
                }
            })
          .catch((error) => {
                console.error('huiyuan 请求出错:', error);
            });
    },
    methods: {
        formatGender(row, column, cellValue) {
            const option = this.genderOptions.find(opt => opt.value === cellValue);
            return option? option.label : '未知';
        },
        formatDate(row, column, cellValue) {
            return dayjs(cellValue).format('YYYY-MM-DD');
        },
        formatUserLevel(row, column, cellValue) {
            return this.userLevelOptions.find(option => option.value === cellValue)?.label || cellValue;
        },
        formatStatus(row, column, cellValue) {
            return this.statusOptions.find(option => option.value === cellValue)?.label || cellValue;
        },
        showDetail(row) {
            console.log('点击行的数据:', row);
            const formattedUser = {
                ...row,
                addTime: dayjs(row.addTime).format('YYYY-MM-DD HH:mm:ss'),
                lastLoginTime: dayjs(row.lastLoginTime).format('YYYY-MM-DD HH:mm:ss'),
                updateTime: dayjs(row.updateTime).format('YYYY-MM-DD HH:mm:ss')
            };
            this.selectedUser = formattedUser;
            this.dialogVisible = true;
        },
        // 重置
        reset() {
            this.inputyan = '';
            this.input7 = '';
            this.input8 = '';
            this.page = 1;
            this.fetchData();
        },
        // 搜索数据
        searchData() {
            if (this.input7) {
                this.getUserById();
            } else {
                this.page = 1;
                this.fetchData();
            }
        },
        async fetchData() {
            const params = {
                username: this.inputyan,
                mobile: this.input8,
                page: this.page,
                limit: this.limit,
                sort: this.sort,
                order: this.order,
                token: this.token
            };
            console.log('请求参数:', params);
            try {
                const res = await searchUserList(params);
                console.log('searchUserList 请求响应:', res);
                if (res.data && Array.isArray(res.data.list)) {
                    const formattedList = res.data.list.map(item => {
                        return {
                            ...item,
                            addTime: dayjs(item.addTime).format('YYYY-MM-DD HH:mm:ss'),
                            lastLoginTime: dayjs(item.lastLoginTime).format('YYYY-MM-DD HH:mm:ss'),
                            updateTime: dayjs(item.updateTime).format('YYYY-MM-DD HH:mm:ss')
                        };
                    });
                    this.list = formattedList;
                    this.total = res.data.total;
                } else {
                    console.error('searchUserList 接口返回的数据格式不符合预期', res.data);
                }
            } catch (error) {
                console.error('数据请求出错:', error);
            }
        },
        async getUserById() {
            if (typeof getUserById!== 'function') {
                console.error('getUserById 不是一个函数，请检查 API 引入和导出');
                return;
            }
            const params = {
                id: parseInt(this.input7, 10), 
                token: this.token
            };
            console.log('根据 id 搜索的请求参数:', params);
            console.log('传递的 id 值:', this.input7);
            try {
                const res = await getUserById(params);
                console.log('getUserById 请求响应:', res);
                if (res.data) {
                    let formattedList;
                    if (Array.isArray(res.data.list)) {
                        formattedList = res.data.list.map(item => {
                            return {
                                ...item,
                                addTime: dayjs(item.addTime).format('YYYY-MM-DD HH:mm:ss'),
                                lastLoginTime: dayjs(item.lastLoginTime).format('YYYY-MM-DD HH:mm:ss'),
                                updateTime: dayjs(item.updateTime).format('YYYY-MM-DD HH:mm:ss')
                            };
                        });
                    } else {
                        formattedList = [res.data].map(item => {
                            return {
                                ...item,
                                addTime: dayjs(item.addTime).format('YYYY-MM-DD HH:mm:ss'),
                                lastLoginTime: dayjs(item.lastLoginTime).format('YYYY-MM-DD HH:mm:ss'),
                                updateTime: dayjs(item.updateTime).format('YYYY-MM-DD HH:mm:ss')
                            };
                        });
                    }
                    this.list = formattedList;
                    this.total = formattedList.length;
                } else {
                    console.error('getUserById 接口返回的数据格式不符合预期', res.data);
                }
            } catch (error) {
                console.error('根据 id 搜索数据出错:', error);
            }
        },
        tableRowClassName({ row, rowIndex }) {
            return rowIndex % 2 === 1? 'dark-row' : '';
        },
        handleSizeChange(newLimit) {
            this.limit = newLimit;
            this.fetchData();
        },
        handleCurrentChange(newPage) {
            this.page = newPage;
            this.fetchData();
        },
        async queding() {
            try {
                const { id, nickname, mobile, gender, userLevel, status } = this.selectedUser;
                const params = {
                    id,
                    nickname,
                    mobile,
                    gender,
                    userLevel,
                    status,
                    token: this.token
                };
                const res = await bianji(params);
                console.log('编辑用户信息响应:', res);
                if (res.data && res.data.code === 200) {
                    this.$message.success('用户信息更新成功');
                    this.dialogVisible = false;
                    this.fetchData(); 
                } else {
                    this.$message.success('用户信息更新成功');
                    this.dialogVisible = false;
                    this.fetchData();
                }
            } catch (error) {
                console.error('编辑用户信息出错:', error);
                this.$message.error('编辑用户信息出错');
            }
        },
        exportData() {
            if (this.list.length === 0) {
                this.$message.warning('暂无数据可导出');
                return;
            }

            const headers = [
                '用户id', '用户昵称', '手机号码', '性别', '生日', '用户等级', '状态'
            ];
            const csvContent = [headers.join(',')];

            this.list.forEach(item => {
                const row = [
                    item.id,
                    item.nickname,
                    item.mobile,
                    this.formatGender(item, null, item.gender),
                    this.formatDate(item, null, item.addTime),
                    this.formatUserLevel(item, null, item.userLevel),
                    this.formatStatus(item, null, item.status)
                ];
                csvContent.push(row.join(','));
            });

            const csvBlob = new Blob([csvContent.join('\n')], { type: 'text/csv;charset=utf-8;' });
            const csvUrl = URL.createObjectURL(csvBlob);
            const link = document.createElement('a');
            link.href = csvUrl;
            link.setAttribute('download', '用户数据.csv');
            link.click();
            URL.revokeObjectURL(csvUrl);
        },
        handleSortChange({ column, prop, order }) {
            if (prop === 'id') {
                this.sort = 'id';
                this.order = order === 'ascending'? 'asc' : 'desc';
                this.page = 1;
                this.fetchData();
            }
        }
    }
};
</script>

<style scoped>
.el-table .warning-row {
    background: oldlace;
}

.el-table .success-row {
    background: #f0f9eb;
}

.container {
    display: flex;
    flex-direction: column;
    padding: 10px;
}

.search-area {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
    
}

.el-input--small .el-input__inner {
    height: 47px;
    line-height: 32px;
}

.table-wrapper {
    flex: 1;
    overflow-y: auto;
    
}

.el-button--small {
    padding: 14px 36px;
    font-size: 12px;
    border-radius: 3px;
}
.pagination-area {
    padding: 10px 0;
    display: flex;
    justify-content: flex-end;
}

.el-input__inner {
    height: 50px;
    line-height: 50px;
}

.dark-row {
    background-color: #f5f5f5;
}

.cell {
    font-size: 18px;
}
.el-tag.el-tag--info {
    background-color: #e8f4ff;
    border-color: #d1e9ff;
    color: #1890ff;
}
.archive-button {
    background-color: #fff; 
    color: #f56c6c; 
    border: 1px solid #f56c6c; 
    padding: 6px 12px; 
    border-radius: 4px; 
    display: inline-flex; 
    align-items: center; 
    justify-content: center; 
    transition: all 0.3s; 
}
.archive-button:hover {
    background-color: #f56c6c; 
    color: #fff; 
}
.el-pagination {
    white-space: nowrap;
    padding: 2px 5px;
    color: #303133;
    font-weight: 700;
    margin-left: 40px;
    margin-top: 22px;
}
</style>